package utils

import config.MyFile
import org.apache.commons.io.FileUtils

import scala.jdk.CollectionConverters._

object getBlastData extends MyFile {

  def main(args: Array[String]): Unit = {
    filterCds
    getCds
    filterPep
    getPep
  }

  def getBlastGenome = {
    val time = System.currentTimeMillis()

    "I:\\alfalfa_db\\fasta".listFile.foreach { x =>
      val name = x.getName.split('.').head
      println(getTime(time))

      var chr = ""
      val line = x.readLines.map { y =>
        if (y.startsWith(">")) {
          chr += y.trim.tail + "-" + name + "\n"
          y.trim + "-" + name
        } else {
          y
        }
      }
      println(name)
      println(getTime(time))
      FileUtils.writeLines("I:/alfalfa_db/blastData/genome/genome.fasta".toFile, line.asJava, true)
      FileUtils.writeStringToFile(s"I:/alfalfa_db/blastData/${name}_chr.txt".toFile, chr)
    }
  }

  def x2 = {
    (1 to 14).foreach { x =>
      val line = s"I:/sgb_db/blastData/${x}_chr.txt".readLines.map { y => x + "-" + y }
      FileUtils.writeLines(s"I:/sgb_db/blastData/chr.txt".toFile, line.asJava, true)
    }
  }

  def filterPep = {
    "I:\\alfalfa_db\\fasta\\pep".listFile.foreach { x =>
      val name = x.getName.split('.').head
      val pep = x.readFileToString.split(">").tail.map { y =>
        val line = y.split("\n")
        val head = line.head
        val i = head.indexOf("gene=")
        head.drop(i + 5) -> line.tail.mkString.split('.').mkString
      }.groupBy(_._1).map { y =>
          ">" + y._1 + "\n" + y._2.maxBy(_._2.length)._2 + "\n"
      }.mkString
      FileUtils.writeStringToFile(x, pep)

    }
  }

  def getPep = {
    "I:\\alfalfa_db\\fasta\\pep".listFile.foreach { x =>
      val pepFile = x.readLines
      FileUtils.writeLines(s"I:/alfalfa_db/blastData/pep/pep.fasta".toFile, pepFile.asJava, true)
    }
  }

  def filterCds = {
    "I:\\alfalfa_db\\fasta\\cds".listFile.foreach { x =>
      val name = x.getName.split('.').head
      val cds = x.readFileToString.split(">").tail.map { y =>
        val line = y.split("\n")
        val head = line.head
        val i = head.indexOf("gene=")
        head.drop(i + 5) -> line.tail.mkString.split('.').head
      }.groupBy(_._1).map { y =>
          ">" + y._1 + "\n" + y._2.maxBy(_._2.length)._2 + "\n"
      }.mkString
      FileUtils.writeStringToFile(x, cds)

    }
  }

  def getCds = {
    "I:\\alfalfa_db\\fasta\\cds".listFile.foreach { x =>
      val cdsFile = x.readLines
      FileUtils.writeLines(s"I:/alfalfa_db/blastData/cds/cds.fasta".toFile, cdsFile.asJava, true)
    }
  }

  def getTime(startTime: Long) = {
    val endTime = System.currentTimeMillis()
    (endTime - startTime) / 1000.0
  }

}

